<template>
  <cu-addCard :inDomStyle="ballStyle" :ballImg="ballImg" :toDomStyle="inDom"></cu-addCard>
  <scroll-view
    class="selectDish"
    :scroll-y="true"
    border-radius="15"
    @scrolltolower="scrolltolower"
    @scroll="scrollChange"
  >
    <view class="dishItemBox" v-for="(item, index) in dataList" :key="item.dishId">
      <view class="img" @click="goComment(item)">
        <uv-image
          :src="item.dishUrl"
          width="192rpx"
          height="192rpx"
          :lazy-load="true"
          :fade-show="true"
          :observeLazyLoad="true"
          mode="aspectFit"
          radius="15rpx"
        >
          <template v-slot:error>
            <view style="font-size: 24rpx">加载失败</view>
          </template>
        </uv-image>
      </view>
      <view class="content">
        <view class="title">{{ item.dishName }}</view>
        <view class="flex">
          <view style="margin-right: 30.77rpx">关注度 {{ item.allFollow || 0 }}</view>
          <view>被选 {{ item.allChoose || 0 }}</view>
        </view>
        <view class="flex">
          <view>评价</view>
          <view>
            <uv-rate
              :allowHalf="true"
              :readonly="true"
              active-color="#FAD20C"
              inactive-color="#DCDEE0"
              gutter="0"
              :value="item.allReview / 2"
            ></uv-rate>
          </view>
        </view>
        <view class="selectBox flex flex-justify-between">
          <view class="flex" @click="onFollow(item, index)">
            <uv-icon
              :name="item.attent ? 'guanzhu' : 'guanzhu-1'"
              custom-prefix="custom-icon"
              size="38rpx"
              :color="item.attent ? '#ff363f' : '#CCCCCC'"
            ></uv-icon>
          </view>
          <view class="select" @click="addCart(index)" v-if="item.flg == 0">选择</view>
          <view class="select" style="background: #cccccc" v-if="item.flg == -1"
            >已选择</view
          >
          <view class="select" style="background: #cccccc" v-if="item.flg == 1"
            >已点菜</view
          >
        </view>
      </view>
    </view>
    <uv-load-more :status="status" />
  </scroll-view>
</template>
<script setup lang="ts">
import {
  getAddBudgetOrder,
  getSaveOneAttention,
  getDeleteOneAttention,
} from "@/service/business/orderingDishes/index";
import debounce from "@/utils/debounce";
import throttle from "@/utils/throttle";
import { SelectDishInfo } from "@/service/business/orderingDishes/type";
import { useUserStore } from "@/store";
const userStore = useUserStore();
/**
 * dataList 菜肴数据列表
 * status 上滑底部状态
 * inDom 购物车动画目标dom
 * animation 是否触发动画 默认是
 */
interface Props {
  dataList?: SelectDishInfo[];
  status?: string;
  inDom?: Object;
  animation?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
  dataList: () => [],
  status: "loading",
  inDom: () => ({}),
  animation: true,
});
// 由于watch监听datalist的改变，去获取dom
watch(
  () => props.dataList.length,
  () => {
   
    getImgDom();
  },
  { deep: true }
);

const emit = defineEmits(["scrolltolower", "addcart", "onfollow", "animationEnd"]);

let query = null;
// 获取imgDom
const getQuery = () => {
  const instance = getCurrentInstance();
  query = uni.createSelectorQuery().in(instance);
};

// 因为在点击时调用query函数获取dom慢导致动画比较卡，所以修改为在dataList改变时和滑动时获取img的位置
function getImgDom() {
  debounce(() => {
    query
      .selectAll(".img")
      .boundingClientRect(async (rects: any) => {
        imgDomList.value = rects;
      })
      .exec();
  }, 500);
}
const imgDomList = ref(null);
// 小球img
const ballImg = ref("");
// 移动小球的值
const ballStyle = reactive({
  left: "0px",
  top: "0px",
});
// 停止滑动时再次获取dom
const scrollChange = () => {
  debounce(() => {
    getImgDom();
  }, 100);
};
// 添加小球
const addCart = (index) => {
  throttle(() => {
    ballImg.value = props.dataList[index].dishUrl;
    getAddBudgetOrderApi(props.dataList[index], index);
    // 不需要动画直接return
    if (!props.animation) {
      return;
    }
    ballStyle.left = imgDomList.value[index].left;
    ballStyle.top = imgDomList.value[index].top;
  });
};
const flag = ref(true);
// 动画
const animationEnd = () => {
  emit("animationEnd");
};
// 触底
const scrolltolower = () => {
  if (flag.value && props.status == "loading") {
    flag.value = false;
    emit("scrolltolower");
    setTimeout(() => {
      flag.value = true;
    }, 2000);
  }
};
// 关注菜品
const onFollow = (item, index) => {
  // item.attent为0是未被关注，为1是被关注
  if (item.attent) {
    getDeleteOneAttentionApi(item.dishCode, index);
  } else {
    getSaveOneAttentionApi(item.dishCode, index);
  }
};
// 将菜肴添加购物车
const getAddBudgetOrderApi = (item: SelectDishInfo, index) => {
  return new Promise((resolve) => {
    getAddBudgetOrder({
      dishName: item.dishName,
      dishCode: item.dishCode,
      dishType: item.dishType,
      dishStyle: item.style,
      userId: userStore.userInfo.user.userId,
    }).then((res) => {
      if (res.retCode === 2000) {
        emit("addcart", { item, index });
      }
    });
  });
};
// 关注菜品
const getSaveOneAttentionApi = (dishCode, index) => {
  return new Promise((resolve) => {
    getSaveOneAttention({
      userId: userStore.userInfo.user.userId,
      dishCode,
    }).then((res) => {
      if (res.retCode === 2000) {
        uni.showToast({
          title: "关注菜品成功",
          icon: "none",
        });
        emit("onfollow", index);
      }
    });
  });
};
// 取消关注菜品
const getDeleteOneAttentionApi = (dishCode, index) => {
  return new Promise((resolve) => {
    getDeleteOneAttention({
      userId: userStore.userInfo.user.userId,
      dishCode,
    }).then((res) => {
      if (res.retCode === 2000) {
        uni.showToast({
          title: "取消关注菜品成功",
          icon: "none",
        });
        emit("onfollow", index);
      }
    });
  });
};

// 查看菜肴信息
const goComment = (item) => {
  const { dishCode, recipedtlId } = item;
  uni.navigateTo({
    url: "/packageOne/pages/dishesDetail/index?code=" + dishCode + "&id=0",
  });
};

onMounted(() => {
  getQuery();
});
</script>

<style lang="scss" scoped>
.selectDish {
  width: 100%;
  height: calc(100% - 69.23rpx);
}
.dishItemBox {
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 192.31rpx;
  padding-right: 30.77rpx;
  margin-bottom: 46.15rpx;
  font-family: PingFang SC, PingFang SC;
  font-size: 23rpx;
  font-weight: 400;
  line-height: 38rpx;
  color: #969799;
  .img {
    width: 192rpx;
    height: 192rpx;
    margin-right: 15.38rpx;
  }

  .content {
    flex: 1;
    .title {
      font-family: PingFang SC, PingFang SC;
      font-size: 31rpx;
      font-weight: 600;
      line-height: 46rpx;
      color: #111111;
    }

    .selectBox {
      margin-top: 23.08rpx;
      .select {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 115rpx;
        height: 46rpx;
        font-family: PingFang SC, PingFang SC;
        font-size: 23rpx;
        font-weight: 400;
        color: #ffffff;
        background: linear-gradient(90deg, #00754a 0%, #006241 100%);
        border-radius: 73rpx 73rpx 73rpx 73rpx;
      }
      .select:active {
        opacity: 0.6;
      }
      .selectActive {
        color: #00754a;
        background: #d4e9e2;
      }
    }
  }
}
</style>
